var fs = require('fs');
var request = require("superagent");
var Excel = require('exceljs');

var num = 200;
var n = 0;

// 任务创建间隔（ms）
var interval = 5000;

var source = 'https://member.ly.com/orderajax/default';

var workbook = new Excel.Workbook();

var ws1 = workbook.addWorksheet("订单信息");
ws1.columns = [
    {header: '项目', width: 10},
    {header: '账户', width: 10},
    {header: 'No.', width: 5},
    {header: '航班信息', width: 45},
    {header: '航班日期', width: 30},
    {header: '下单时间', width: 25},
    {header: '订单号', width: 25},
    {header: '订单状态', width: 10},
    {header: '金额', width: 10},
    {header: '金额明细', width: 30},
    {header: '乘机人', width: 20},
    {header: '航班号', width: 10},
    {header: '舱等机型', width: 30},
    {header: '航空公司', width: 10}
];
ws1.getRow(1).font = {
    bold: true
};

fs.readFile('cookie.ini', 'utf-8', function (err, data) {
    if (err) {
        console.log("Error: " + err);
    } else {
        if (data.length > 10) {
            startRequest(source, data, num);
        } else {
            console.log('请设置Cookie文件');
        }
    }
});

function startRequest(url, cookie, num) {
    console.log('初始化系统');
    for (var j = 1; j <= Math.ceil(num / 10); j++) {
        setTimeout(function (j) {
            console.log('创建任务：' + j);

            request.get(url + '?OrderFilter=0&ProjectTag=5&DateType=0&PageIndex=' + j)
                .set("Cookie", cookie)
                .end(function (err, res) {
                    if (err) {
                        console.log("Error: " + err);

                        process.exit(0);
                    } else {
                        var resJson = JSON.parse(res.text);

                        if (resJson.Success === true && resJson.Code === 200) {
                            if (resJson.ReturnValue !== undefined) {
                                resJson = resJson.ReturnValue;
                                // console.log('本账号共有订单：' + resJson.OrderListCount);

                                if (num > resJson.OrderListCount) {
                                    num = resJson.OrderListCount;
                                }

                                resJson = resJson.OrderDetailList;

                                for (var i = 0; i < resJson.length; i++) {
                                    resJson[i].no = i + (j - 1) * 10 + 1;

                                    // 获取订单详细信息
                                    getDetail(resJson[i], cookie);
                                }
                            } else {
                                console.log('无法解析数据，请更新程序');
                                process.exit(1);
                            }
                        } else {
                            console.log('获取数据失败，请更新Cookie');
                            process.exit(2);
                        }
                    }
                });
        }, interval * j, j);
    }
}

function getDetail(buffer, cookie) {
    var no = buffer.no;
    var SerialId = buffer.SerialId;
    var ChieseOrderStatus = buffer.ChieseOrderStatus;
    var ProductPrice = buffer.ProductPrice;
    var ProductName = buffer.ProductName;
    var FirstDesc = buffer.FirstDesc;
    var FlightNo = buffer.ExtendData.FlightNo;
    var PassengerNames = buffer.ExtendData.PassengerNames;

    request.get('https://www.ly.com/flights/orderdetail?serialid=' + SerialId)
        .set("Cookie", cookie)
        .end(function (err, res) {
            if (err) {
                console.log("Error: " + err);

                process.exit(3);
            } else {
                var dom = res.text;

                // 简化dom
                var simStart = dom.indexOf('<div class="detail-right">');
                var simEnd = dom.indexOf('));</script><script src=');
                if (simStart !== -1 && simEnd !== -1) {
                    dom = dom.substr(simStart, simEnd - simStart);
                }

                var label = '';
                var start = -1;
                var end = -1;

                var OrderTime = '获取失败';
                var regOrderTime = /<div(.*?)><div class="tit"(.*?)>预订时间:<\/div>\s(.*?)[\s]+<\/div><\/div>/gi;
                var resOrderTime = dom.match(regOrderTime);
                if (resOrderTime !== null) {
                    label = '</div>';
                    start = resOrderTime[0].indexOf(label);
                    start += label.length;
                    while (resOrderTime[0].charAt(start) === "\n" || resOrderTime[0].charAt(start) === ' ') {
                        start++;
                    }
                    end = resOrderTime[0].indexOf('\n', start);

                    if (start !== -1 && end !== -1) {
                        OrderTime = resOrderTime[0].substr(start, end - start);
                    }
                }

                var FlightCompany = '获取失败';
                var regFlightCompany = /<span class="airport f-w-b"(.*?)><em(.*?)><\/em>\s(.*?)[\s]+<\/span>/gi;
                var resFlightCompany = dom.match(regFlightCompany);
                if (resFlightCompany !== null) {
                    label = '</em>';
                    start = resFlightCompany[0].indexOf(label);
                    start += label.length;
                    while (resFlightCompany[0].charAt(start) === "\n" || resFlightCompany[0].charAt(start) === ' ') {
                        start++;
                    }
                    end = resFlightCompany[0].indexOf('\n', start);

                    if (start !== -1 && end !== -1) {
                        FlightCompany = resFlightCompany[0].substr(start, end - start);
                    }
                }

                var CabinName = '获取失败';
                var regCabinName = /<div(.*?)><span class="p-r"(.*?)>(.*?)<\/span> <span(.*?)>(.*?)<\/span><\/div><\/div>/gi;
                var resCabinName = dom.match(regCabinName);
                if (resCabinName !== null) {
                    CabinName = resCabinName[0].replace(/<[^>]+>/g, "");
                }

                var account = dom.indexOf('"' + SerialId + '"');
                if (account !== -1) {
                    account = dom.substr(account).split('","');
                    if (account.length >= 2) {
                        account = account[account.length - 2];
                    } else {
                        account = '获取失败';
                    }
                }

                orderDetailFee(SerialId, ['国内机票', account, no, ProductName, FirstDesc, OrderTime, SerialId, ChieseOrderStatus, ProductPrice, PassengerNames, FlightNo, CabinName, FlightCompany]);
            }
        });
}

function orderDetailFee(SerialId, buffer) {
    request.post('https://www.ly.com/flights/api/order/orderdetailfee')
        .set("tcsectoken", '027093039245106135243230197030056045202015212082190244053038211091054223246238095172074148068195091131052177225139141156068169107072219105044138127221143226198081138003204059159017138172156242248090123150025228086029')
        .type('form')
        .send({
            serialNo: SerialId,
            flat: 1,
            plat: 1,
            isFromKylin: 1,
            refid: "0"
        })
        .end(function (err, res) {
            n++;

            if (err) {
                console.log("Error: " + err);

                process.exit(4);
            } else {
                var resJson = JSON.parse(res.text);

                if (resJson.body.errCode !== 0) {
                    console.log(resJson.body.errMsg + '，请重新获取 tcsectoken');

                    process.exit(5);
                }

                var fee = resJson.body.transInfos[0].itemDetails;

                var PriceDetail = '';
                for (var i = 0; i < fee.length; i++) {
                    PriceDetail += fee[i].itemName + fee[i].itemUnitPrice + ' ';
                }

                buffer.splice(9, 0, PriceDetail);
                ws1.addRow(buffer);

                console.log(SerialId + ' --- OK');
            }

            if (n >= num) {
                workbook.xlsx.writeFile(num + ' - export.xlsx')
                    .then(function () {
                        console.log('OK: ' + num + ' - export.xlsx');
                    });
            }
        })
}
